//
//  WriteFileExtension.swift
//  JKTools
//
//  Created by 姜奎 on 2024/10/15.
//

import Foundation

public
extension Data {
    func write(to path: String) throws {
        try self.write(to: URL(fileURLWithPath: path), options: .atomicWrite)
    }

    static func read(to path: String) -> Data? {
        return FileManager.default.contents(atPath: path)
    }

    func write(to url: URL) throws {
        try self.write(to: url, options: .atomicWrite)
    }

    static func read(to url: URL) throws -> Data {
        return try Data(contentsOf: url)
    }

    func stringValue() -> String? {
        return String(data: self, encoding: .utf8)
    }

    func dictValue<T>() throws -> T {
        return try JSONSerialization.jsonObject(with: self, options: .mutableContainers) as! T
    }

    func arrayValue<T>() throws -> T {
        return try JSONSerialization.jsonObject(with: self, options: .mutableContainers) as! T
    }

    func objectValue<T: Decodable>() throws -> T {
        return try JSONDecoder().decode(T.self, from: self)
    }
}

public
extension String {
    func dataValue() -> Data? {
        return self.data(using: .utf8)
    }
}

public
extension Dictionary {
    func dataValue() throws -> Data {
        return try JSONSerialization.data(withJSONObject: self, options: .fragmentsAllowed)
    }
}

public
extension Array {
    func dataValue() throws -> Data {
        return try JSONSerialization.data(withJSONObject: self, options: .fragmentsAllowed)
    }
}

public
extension Encodable {
    func dataValue() throws -> Data {
        return try JSONEncoder().encode(self)
    }
}
